<?php
/***
*
* Class: OrderService //订单处理服务
* Author: Jason ZHENG
* Data: 2018-07-05
*
***/
namespace App\Service;

use App\Service\DataReturnService as DRS;
use App\Service\YoppayService;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Session; 
use App\Common\Base;
use App\Validator\OrderValidator;

class OrderService
{
	//生成分笔订单
	public static function makeUnitOrders($order_id)
	{
		$order = DB::table('orders')->where(['id' => $order_id])->first();
		$totalPrice = $order->total_price-$order->coupon_price;
        $unitPrice = 10000;
		$unitOrderCount = intval(floor($totalPrice/$unitPrice));
		$restPirce = $totalPrice%$unitPrice;

		for($i=1 ; $i<=$unitOrderCount; $i++)
		{
			$data = ['order_id' => $order_id,'user_id'=>$order->user_id, 'batchcode' => $order->batchcode, 'price'=>round($unitPrice,2), 'pay_batchcode'=>$order->batchcode.$i, 'create_time' => date('Y-m-d H:i:s')];
			if(! (DB::table('unit_order')->insert($data)))
				return false;
		}
		if($restPirce != 0){
			$dataRest = ['order_id' => $order_id,'user_id'=>$order->user_id, 'batchcode' => $order->batchcode, 'price'=>round($restPirce,2), 'pay_batchcode'=>$order->batchcode.$i, 'create_time' => date('Y-m-d H:i:s')];
			if(! (DB::table('unit_order')->insert($dataRest)))
				return false;
		}

		return true;
		
	}
	// 生成自家订单
	public static function make_own_order($user,$postData,$products,$coupon_price)
    {   
        //生成订单号
        $batchcode = date('YmdHis').str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);

        DB::beginTransaction();
        try {
            //添加新的订单
            $order_data = [
                'system_id'         => 1,
                'business_id'       => $user['business_id'],
                'type'              => 3, //小程序
                'batchcode'         => $batchcode,
                'user_id'           => $user['id'],
                'total_price'       => $postData['total_price'],
                'coupon_id'         => isset($postData['ticket_id']) ? $postData['ticket_id']: null,
                'coupon_price'      => $coupon_price,
                'delivery_id'       => $postData['delivery_id'],
                'payment_status'    => 0,  //未支付
                'status'            => 1, //待付款
                'last_time'         => date('Y-m-d H:i:s'),
                'createtime'        => date('Y-m-d H:i:s'),
                'remark'            => isset($postData['remark']) ? $postData['remark'] : null,
                'pay_code'          => isset($postData['pay_code']) ? $postData['pay_code'] : 0,

            ];
            $order_id = DB::table('orders')->insertGetId($order_data);
       
            foreach ($products as $product) 
            {
                //给每件商品添加订单详情
                $order_info_data = [
                        'system_id'             => 1,
                        'business_id'           => $user['business_id'],
                        'user_id'               => $user['id'],
                        'batchcode'             => $batchcode,
                        'info_batchcode'        => $batchcode.rand(100,999),
                        'delivery_id'           => $postData['delivery_id'],
                        'product_id'            => $product['id'],
                        'product_name'          => $product['product_name'],
                        'price'                 => $product['price'],
                        'cost_price'            => $product['price'],
                        'peer_price'            => $product['peer_price'],
                        'status'                => 1, // 待付款
                        'quantity'              => 1,
                        'last_time'             => date('Y-m-d H:i:s'),
                        'payment_status'        => 0,
                        'createtime'            => date('Y-m-d H:i:s'),
                        'is_prepay'             => 0,
                        'sale_date'             => date('Y-m-d H:i:s'),
                        'procurement_status'    => $product['procurement_status'],
                    ];
                
                $order_info_id = DB::table('orders_info')->insertGetId($order_info_data);
               
                //所有用户的购物车去掉该商品
                DB::table('cart')->where(['product_id' => $product['id']])->update(['state' => 1]);

                //同步该商品的商品都要下架
                DB::table('product')->where(['source_product_id' => $product['id']])->update(['is_onsale' => 0, 'is_sold_business' => 1]);

                //改变商品现有状态 和 原始商品的状态,下架，出全网
                if($product['product_state'] == 1){
                    DB::table('product')->where(['id' => $product['id']])->update(['product_state' => 5]);
                    if($product['is_synchro'] == 1){
                        DB::table('product')->where(['id' => $product['source_product_id']])->update(['is_onsale' => 0, 'is_network' => 0, 'product_state' => 5]);
                    }
                }elseif($product['product_state'] == 2){
                    DB::table('product')->where(['id' => $product['id']])->update(['product_state' => 6]);
                    if($product['is_synchro'] == 1){
                        DB::table('product')->where(['id' => $product['source_product_id']])->update(['is_onsale' => 0, 'is_network' => 0,'product_state' => 6]);
                    }
                }elseif($product['product_state'] == 3){
                    DB::table('product')->where(['id' => $product['id']])->update(['product_state' => 7]);
                    if($product['is_synchro'] == 1){
                        DB::table('product')->where(['id' => $product['source_product_id']])->update(['is_onsale' => 0, 'is_network' => 0, 'product_state' => 7]);
                    }
                }elseif($product['product_state'] == 4){
                    DB::table('product')->where(['id' => $product['id']])->update(['product_state' => 8]);
                    if($product['is_synchro'] == 1){
                        DB::table('product')->where(['id' => $product['source_product_id']])->update(['is_onsale' => 0, 'is_network' => 0, 'product_state' => 8]);
                    }
                }else{
                    DB::rollBack();
                    return DRS::returnError(1000,'该商品不在可售状态！',$product);
                }
            }

            //如果订单总价大于一万，生成每笔一万多小订单
            if($postData['total_price'] > 10000){
                $unitOrders = self::makeUnitOrders($order_id);
                if(!$unitOrders){
                    DB::rollBack();
                    return DRS::returnError(1000,'生成分笔订单出错！',$unitOrders);
                }
            }
                
            DB::commit();
        } catch(\Exception $exception) {
            DB::rollBack();
            return DRS::returnError(1000,'生成订单出错！',$exception);
        }
        return DRS::returnOk(['batchcode' => $batchcode]);
    }

    // 生成产品原商户的订单
    public static function make_others_order($user,$postData,$products,$business_id,$original_business_id)
    {
        $batchcode = date('YmdHis').str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);
        $total_price = 0;
        foreach ($products as $key => $product) {
            $total_price = $total_price + $product['peer_price'];
        }
        
        DB::beginTransaction();
        try {
            //添加新的订单
            $order_data = [
                'system_id'         => 1,
                'business_id'       => $business_id,
                'type'              => 3, //小程序
                'batchcode'         => $batchcode,
                'user_id'           => $original_business_id,
                'total_price'       => $total_price,
                'payment_status'    => 0,  //未支付
                'status'            => 1, //待付款
                'last_time'         => date('Y-m-d H:i:s'),
                'createtime'        => date('Y-m-d H:i:s'),
                'remark'            => isset($postData['remark']) ? $postData['remark'] : null,
                'pay_code'          => isset($postData['pay_code']) ? $postData['pay_code'] : 0,
            ];
            $order_id = DB::table('orders')->insertGetId($order_data);
          
            foreach ($products as $product) 
            {
                if($product['is_autodeliver'] == 1){
                    // 如是自发货，则给商家地址
                    $delivery_id = $product['delivery_id'];
                }else{
                    // 如果是代发货，则给客户地址
                    $delivery_id = $postData['delivery_id'];
                }
                //给每件商品添加订单详情
                $order_info_data = [
                    'system_id'             => 1,
                    'business_id'           => $business_id,
                    'user_id'               => $original_business_id,
                    'batchcode'             => $batchcode,
                    'info_batchcode'        => $batchcode.rand(100,999),
                    'product_id'            => $product['source_product_id'],
                    'product_name'          => $product['product_name'],
                    'original_price'        => $product['cost_price'],
                    'price'                 => $product['peer_price'],
                    'delivery_id'           => $delivery_id,
                    'cost_price'            => $product['peer_price'],
                    'peer_price'            => $product['peer_price'],
                    'status'                => 1, // 待付款
                    'quantity'              => 1,
                    'last_time'             => date('Y-m-d H:i:s'),
                    'payment_status'        => 0,
                    'createtime'            => date('Y-m-d H:i:s'),
                    'is_prepay'             => 0,
                    'sale_date'             => date('Y-m-d H:i:s'),
                    'procurement_status'    => $product['procurement_status'],
                ];
                $order_info_id = DB::table('orders_info')->insertGetId($order_info_data);
            }    
            DB::commit();
        } catch(\Exception $exception) {
            DB::rollBack();
            return DRS::returnError(1000,'生成原商户订单出错！',$exception);
        }
        return DRS::returnOk(['batchcode' => $batchcode]);
    }
    // 取消订单
    public static function removeOrder($batchcode, $user_id)
    {
        // 更改订单状态为关闭交易
        DB::table('orders')
            ->where(['batchcode' => $batchcode, 'user_id'=> $user_id])
            ->update(['status' => 7, 'last_time' => date('Y-m-d H:i:s')]);

        // 更改订单详情的订单状态为关闭交易
        DB::table('orders_info')
            ->where(['batchcode' => $batchcode, 'user_id'=> $user_id])
            ->update(['status' => 7,  'last_time' => date('Y-m-d H:i:s')]);

        // 取消原始商家的订单
        $rmSourceOrder = self::removeSourceOrder($batchcode);
        if($rmSourceOrder['code'] != 666){
            return $rmSourceOrder;
        }

        // 更改商品状态为四种对应的未售
        $updateProdState = self::updateProductState($batchcode, $user_id);
        if($updateProdState['code'] != 666){
            return $updateProdState;
        }

        return DRS::returnOk('取消订单成功');

    }

    // 取消原始商家的订单
    public static function removeSourceOrder($batchcode)
    {
        // 找到所有的订单详情
        $order_info = DB::table('orders_info')
                ->where(['batchcode' => $batchcode])
                ->get();
        foreach ($order_info as $key => $orderI) 
        {   
            // 找到每个订单详情的产品
            $product = DB::table('product')
                ->where(['id' => $orderI->product_id])
                ->first();
            // 如果是同步商品
            if($product->is_synchro ==1 )
            {   
                // 找到原始商品
                $sourceProd = DB::table('product')
                ->where(['id' => $product->source_product_id])
                ->first();
                // 找到原始商品的订单 并更改订单状态为关闭交易
                $sorceOrder = DB::table('orders')
                ->where(['business_id' => $sourceProd->business_id, 'user_id' => $orderI->business_id, 'status' => 1])
                ->update(['status' => 7, 'last_time' => date('Y-m-d H:i:s')]);
                // 找到原始商品的订单详情 并更改订单状态为关闭交易
                $sorceOrderInfo = DB::table('orders_info')
                ->where(['business_id' => $sourceProd->business_id, 'user_id' => $orderI->business_id,'product_id'=>$sourceProd->id, 'status' => 1])
                ->update(['status' => 7, 'last_time' => date('Y-m-d H:i:s')]);

                if($sorceOrder && $sorceOrderInfo){
                    return DRS::returnOk(['batchcode' => $batchcode]);
                }else{
                    return DRS::returnError(1000,'取消原商户订单出错！',$batchcode);
                }
            }
        }
        return DRS::returnOk('取消原始商家的订单成功');
    }

    // 更改商品状态为四种对应的未售
    public static function updateProductState($batchcode, $user_id)
    {
        $ordersInfo = DB::table('orders_info as oi')
                ->where(['oi.batchcode' => $batchcode])
                ->leftJoin('product as p','p.id','=','oi.product_id')
                ->get()
                ->toArray();
        $orderInfos = array_map('get_object_vars', $ordersInfo);
  
        // 更改商品状态为四种对应的未售
        foreach ($orderInfos as $oinfo) 
        { 
            if($oinfo['product_state'] == 5){
                DB::table('product')
                    ->where(['id' => $oinfo['product_id']])
                    ->update(['product_state' => 1, 'updatetime' =>date('Y-m-d H:i:s')]);
                // 如果是同步商品，改回原始商品的状态
                if($oinfo['is_synchro'] == 1){
                    DB::table('product')
                    ->where(['id' => $oinfo['source_product_id']])
                    ->update(['is_onsale' => 1, 'is_network' => 1,'product_state' => 1,'updatetime' =>date('Y-m-d H:i:s')]);
                }else{
                    // 如果是自有商品，改回其他同步改商品的状态
                    DB::table('product')
                    ->where(['source_product_id' => $oinfo['product_id']])
                    ->update(['product_state' => 1, 'is_sold_business'=> 0,'updatetime' =>date('Y-m-d H:i:s')]);
                }
            }
            elseif($oinfo['product_state'] == 6 ){
                DB::table('product')
                    ->where(['id' => $oinfo['product_id']])
                    ->update(['product_state' => 2, 'updatetime' =>date('Y-m-d H:i:s')]);

                // 如果是同步商品，改回原始商品的状态
                if($oinfo['is_synchro'] == 1){
                    DB::table('product')
                    ->where(['id' => $oinfo['source_product_id']])
                    ->update(['is_onsale' => 1, 'is_network' => 1,'product_state' => 2,'updatetime' =>date('Y-m-d H:i:s')]);
                }else{
                    // 如果是自有商品，改回其他同步改商品的状态
                    DB::table('product')
                    ->where(['source_product_id' => $oinfo['product_id']])
                    ->update(['product_state' => 2, 'is_sold_business'=> 0,'updatetime' =>date('Y-m-d H:i:s')]);
                }
            }elseif($oinfo['product_state'] == 7 ){
                DB::table('product')
                    ->where(['id' => $oinfo['product_id']])
                    ->update(['product_state' => 3, 'updatetime' =>date('Y-m-d H:i:s')]);
                // 如果是同步商品，改回原始商品的状态
                if($oinfo['is_synchro'] == 1){
                    DB::table('product')
                    ->where(['id' => $oinfo['source_product_id']])
                    ->update(['is_onsale' => 1, 'is_network' => 1,'product_state' => 3,'updatetime' =>date('Y-m-d H:i:s')]);
                }else{
                    // 如果是自有商品，改回其他同步改商品的状态
                    DB::table('product')
                    ->where(['source_product_id' => $oinfo['product_id']])
                    ->update(['product_state' => 3, 'is_sold_business'=> 0,'updatetime' =>date('Y-m-d H:i:s')]);
                }
            }elseif($oinfo['product_state'] == 8 ){
                DB::table('product')
                    ->where(['id' => $oinfo['product_id']])
                    ->update(['product_state' => 4, 'updatetime' =>date('Y-m-d H:i:s')]);
                // 如果是同步商品，改回原始商品的状态
                if($oinfo['is_synchro'] == 1){
                    DB::table('product')
                    ->where(['id' => $oinfo['source_product_id']])
                    ->update(['is_onsale' => 1, 'is_network' => 1, 'product_state' => 4,'updatetime' =>date('Y-m-d H:i:s')]);
                }else{
                    // 如果是自有商品，改回其他同步改商品的状态
                    DB::table('product')
                    ->where(['source_product_id' => $oinfo['product_id']])
                    ->update(['product_state' => 4, 'is_sold_business'=> 0,'updatetime' =>date('Y-m-d H:i:s')]);
                }
            }
        }
        return DRS::returnOk('更改商品状态成功');
    }

    // 确认收货，资金确认
    public static function confirmOrder($batchcode, $user_id)
    {
        // 向易宝发送订单确认，并给商户的相应资金解冻
        $result = self::confirmMerchantOrderCurrency($batchcode);
        if($result['code'] != 666){
           return  $result;
        }
        
        // 更改订单状态为交易成功
        DB::table('orders')
            ->where(['batchcode' => $batchcode, 'user_id'=> $user_id])
            ->update(['status' => 6, 'last_time' => date('Y-m-d H:i:s')]);

        // 更改订单详情的订单状态为交易成功
        DB::table('orders_info')
            ->where(['batchcode' => $batchcode, 'user_id'=> $user_id])
            ->update(['status' => 6,  'last_time' => date('Y-m-d H:i:s')]);
        

        $ordersInfo = DB::table('orders_info')
            ->where(['batchcode' => $batchcode])
            ->get()
            ->toArray();
        $orders_info = array_map('get_object_vars', $ordersInfo);
        foreach ($orders_info as $oinfo) 
        { 
            $product = DB::table('product')
                    ->where(['id' => $oinfo['product_id']])
                    ->first();
            // 更改商品状态为已售
            DB::table('product')
                    ->where(['id' => $oinfo['product_id']])
                    ->update(['product_state' => 14, 'updatetime' =>date('Y-m-d H:i:s')]);
            if($product->is_synchro == 1){
                // 如果是同步商品的订单，要将原订单的状态改为已完成
                $updateOriginalOrder = self::updateOriginalOrder($product->source_product_id);
            }
            
            
        }
        
        return DRS::returnOk('订单确认成功');
    }

    // 确认收货，分笔订单资金确认
    public static function confirmUnitOrder($pay_batchcode)
    {
        // 向易宝发送订单确认，并给商户的相应资金解冻
        $result = self::confirmMerchantUnitOrderCurrency($pay_batchcode);
        if($result['code'] != 666){
           return  $result;
        }

        $unitOrder = DB::table('unit_order')->where(['pay_batchcode' => $pay_batchcode])->update(['is_confirm' => 1, 'confirm_time' => date('Y-m-d H:i:s')]);
        if($unitOrder){
            return DRS::returnOk('分笔订单确认成功');
        }
        else{
            return DRS::returnError(1011,'分笔订单确认失败!');
        }
    }

    //将原订单的状态改为已完成
    public static function updateOriginalOrder($product_id)
    {
        $orderInfo = DB::table('orders_info')
            ->where(['product_id' => $product_id, 'status' => 3])
            ->first();
        // 更改订单详情的订单状态为交易成功
        DB::table('orders_info')
            ->where(['product_id' => $product_id, 'status' => 3])
            ->update(['status' => 6,  'last_time' => date('Y-m-d H:i:s')]);
        // 更改订单状态为交易成功
        DB::table('orders')
            ->where(['batchcode' => $orderInfo->batchcode])
            ->update(['status' => 6, 'last_time' => date('Y-m-d H:i:s')]);

        // 更改商品状态为已售
        DB::table('product')
            ->where(['id' => $product_id])
            ->update(['product_state' => 14, 'updatetime' =>date('Y-m-d H:i:s')]);

    }

    // 向易宝发送订单确认，并给商户的相应资金解冻
    public static function confirmMerchantOrderCurrency($batchcode)
    {
        // 获取order
        $order = DB::table('orders')->where(['batchcode' => $batchcode])->first();
        if($order == null){
            return DRS::returnError(1001,'找不到该订单!');
        }
        // 获取商户信息
        $business = DB::table('business')->where(['business_id' => $order->business_id])->first();
        if($business == null){
            return DRS::returnError(1002,'找不到该订单的商户!');
        }
        // 向易宝发送资金确认
        $result = YoppayService::confirmYeepayCurrency($business->parentMerchantNo,$business->merchantNo,$batchcode,$order->uniqueOrderNo);
        if($result['code'] != 'OPR00000'){
            return DRS::returnError(1003,'易宝资金确认失败', $result);
        }
        
        // 将这条订单涉及的资金分配商户的冻结资金解冻
        $merchantCurrency = DB::table('merchant_currency')->where(['batchcode' => $batchcode])->update(['state'=>1,'confirm_time' => date('Y-m-d H:i:s'), 'updatetime' => date('Y-m-d H:i:s')]);

        //将同步商品的商家涉及的资金的冻结资金解冻
        $otherMerchtCurrency = self::comfirmOtherMerchantCurrency($batchcode);
        
        if($merchantCurrency){
            return DRS::returnOk(666,'资金确认和解冻成功');
        }else{
            return DRS::returnError(1004,'资金解冻失败');
        }
        
    }

    public static function comfirmOtherMerchantCurrency($batchcode)
    {
        $ordersInfo = DB::table('orders_info')
            ->where(['batchcode' => $batchcode])
            ->get()
            ->toArray();
        $orders_info = array_map('get_object_vars', $ordersInfo);
        foreach ($orders_info as $oinfo) 
        { 
            $product = DB::table('product')
                    ->where(['id' => $oinfo['product_id']])
                    ->first();
            if($product->is_synchro == 1){
                // 如果是同步商品，找到原有商品的订单详情
                $orderInfo = DB::table('orders_info')
                            ->where(['product_id' => $product->source_product_id, 'status' => 3])
                            ->first();
                //找到原有商家的订单资金
                DB::table('merchant_currency')->where(['batchcode' => $orderInfo->batchcode])->update(['state'=>1,'confirm_time' => date('Y-m-d H:i:s'), 'updatetime' => date('Y-m-d H:i:s')]);
                

            }
        }
    }

    // 向易宝发送订单确认，并给商户的相应资金解冻
    public static function confirmMerchantUnitOrderCurrency($pay_batchcode)
    {
        // 获取order
        $unitOrder = DB::table('unit_order')->where(['pay_batchcode' => $pay_batchcode])->first();
        if($unitOrder == null){
            return DRS::returnError(1001,'找不到该分笔订单!');
        }
        if($unitOrder->transaction_id == null){
            return DRS::returnError(1001,'该分笔订单不存在易宝订单!');
        }
        if($unitOrder->payment_status != 1){
            return DRS::returnError(1001,'该分笔订单未支付!');
        }
        $order = DB::table('orders')->where(['batchcode' => $unitOrder->batchcode])->first();
        if($order == null){
            return DRS::returnError(10011,'找不到该分笔订单的总订单!');
        }
        // 获取商户信息
        $business = DB::table('business')->where(['business_id' => $order->business_id])->first();
        if($business == null){
            return DRS::returnError(1002,'找不到该订单的商户!');
        }
        if($business->parentMerchantNo == null || $business->merchantNo == null ){
            return DRS::returnError(10021,'该订单的商户未绑定易宝商户编号!');
        }
        // 向易宝发送资金确认
        $result = YoppayService::confirmYeepayCurrency($business->parentMerchantNo,$business->merchantNo,$pay_batchcode,$unitOrder->transaction_id);
        if($result['code'] != 'OPR00000'){
            return DRS::returnError(1003,'易宝资金确认失败', $result);
        }
   
        return DRS::returnOk(666,'资金确认和解冻成功');
    }
}